/*
 * Serial.cpp
 *
 *  Created on: 12-mrt.-2014
 *      Author: thomas & Johan
 */

#include "Serial.h"
#include <string.h>
#include <iostream>
using namespace std;



// ---------------------------------------------------------------------------
Serial::~Serial()
{
        // Close the filedescriptor
        close(fd);
}

// ---------------------------------------------------------------------------

Serial::Serial(){

	struct termios old_flags;
	struct termios term_attr;

	//open port
	if((this->fd = open(PORT, O_RDWR | O_NOCTTY | O_NDELAY)) == -1){
		printf("ERROR: Can't open the port.\n");
	}
	else printf("SUCCESS: port is open!\n");

	//get port attributes
	if(tcgetattr(this->fd, &term_attr)){
		printf("ERROR: Can't get port attributes.\n");
	}
	else printf("SUCCESS: port attributes get!\n");

	//set the baud rate
	cfsetispeed(&term_attr, B38400);
	cfsetospeed(&term_attr, B38400);

	//set some flags
	term_attr.c_cflag |= (CLOCAL | CREAD);
	term_attr.c_cflag &= ~PARENB;
	term_attr.c_cflag &= ~CSTOPB;
	term_attr.c_cflag &= ~CSIZE;
	term_attr.c_cflag |= CS8;

	//send the new attributes to the port
	if(tcsetattr(this->fd, TCSANOW, &term_attr))
		printf("ERROR: Can't set port attributes.\n");
	else printf("SUCCESS: port attributes set!\n");



}


int Serial::sWrite(string command){
	const char *temp = command.c_str();
	char cmd[13];
	strncpy(cmd,temp,12);	//never copy more than the destination can carry
	int len = strlen(cmd);
	cmd[len] = 13;		//add CR
	cmd[len+1] = '\0';	//restore '\0' to complete string

	int written = write(this->fd, cmd, strlen(cmd));

	if(written <= 0){
		printf("ERROR: chars written = %d\n", written);
		return 1;
	}

	printf("SUCCESS: executed %s\n", cmd);

	return 0;
}

int Serial::sRead(char *result){
	//memset(result,'\0',SERIAL_BUF_LEN*sizeof(char));

	//don't block the reading from the port
	fcntl(this->fd, F_SETFL, O_NONBLOCK);

	int numRead = read(this->fd, result, SERIAL_BUF_LEN);
	if(numRead < 0){
		printf("ERROR: can't read from serial!\n");
		return 0;
	}

	printf("SUCCESS: read %d chars!\n", numRead);

	return numRead;

}
